﻿using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PhotoGallery.Utils
{
    public static class LoginHelper
    {
        private static readonly char[] charArr = { 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '<', '>', '?', '#', '$', '%', '@', '&', '!', '(', ')' };


        /// <summary>
        /// 验证密码
        /// </summary>
        /// <param name="password">密码原文</param>
        /// <param name="passwdHash">密码hash</param>
        /// <param name="salt">盐</param>
        /// <returns></returns>
        public static bool VerifyHashedPassword(string password, string passwdHash, string salt)
        {
            byte[] saltBytes = Encoding.UTF8.GetBytes(salt);

            byte[] hashBytes = KeyDerivation.Pbkdf2(
                password: password,
                salt: saltBytes,
                prf: KeyDerivationPrf.HMACSHA1,
                iterationCount: 1000,
                numBytesRequested: 256 / 8
            );

            string hashText = BitConverter.ToString(hashBytes).Replace("-", string.Empty);
            return hashText == passwdHash;
        }

        public static string EncryptPassword(string password, string salt)
        {
            if (string.IsNullOrEmpty(password) || string.IsNullOrEmpty(salt))
            {
                throw new ArgumentNullException("密码或盐不能为空");
            }

            byte[] saltBytes = Encoding.UTF8.GetBytes(salt);

            byte[] hashBytes = KeyDerivation.Pbkdf2(
                password: password,
                salt: saltBytes,
                prf: KeyDerivationPrf.HMACSHA1,
                iterationCount: 1000,
                numBytesRequested: 256 / 8
            );

            string hashText = BitConverter.ToString(hashBytes).Replace("-", string.Empty);
            return hashText;
        }


        public static string GenerateSalt(uint len = 8)
        {
            if (len < 1)
            {
                throw new ArgumentOutOfRangeException("参数值需大于0");
            }
            byte[] buf = new byte[4];
            using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
            {
                rng.GetBytes(buf);

            }
            var seed = BitConverter.ToInt32(buf, 0);
            var random = new Random(seed);
            char[] saltChArr = new char[len];
            for (var i = 0; i < len; i++)
            {
                var num = random.Next() % (charArr.Length);
                saltChArr[i] = charArr[num];
            }
            return new string(saltChArr);
        }


    }
}
